package com.hw.paltfrom.service.system;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hw.paltfrom.mapper.*;
import com.hw.paltfrom.pack.ResponseResult;
import com.hw.paltfrom.pojo.*;
import com.hw.paltfrom.rescode.HWSystemCode;
import com.hw.paltfrom.utils.*;
import com.hw.paltfrom.vo.BaseOverrunstationVO;
import com.hw.paltfrom.vo.LoginRequestVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;

@Service
public class UserLoginService {

    @Autowired
    HwBaseUserMapper baseUserMapper;

    @Autowired
    HwBaseAuthorizeMapper baseAuthorizeMapper;

    @Autowired
    HwBaseUserRelationMapper baseUserRelationMapper;

    @Autowired
    HwBaseOverrunstationMapper overrunstationMapper;
    @Autowired
    HwBaseOverrunstationDutyMapper hwBaseOverrunstationDutyMapper;

    @Autowired
    HwBaseCountycoreMapper countycoreMapper;

    @Autowired
    HwBaseAreaMapper areaMapper;
//    private int cookieMaxAge;


    /*public Map<String, Object> addUser(LoginRequestVO loginRequestVO) {
        //创建user对象
        HwBaseUser hwBaseUser = new HwBaseUser();
        hwBaseUser.setfAccount(loginRequestVO.getfAccount());//添加用户名
        HwBaseUser one = baseUserMapper.selectOne(hwBaseUser);//根据用户名查询是否重复
        HashMap<String, Object> resultjson = new HashMap<>();//返回提示信息
        if (one != null) {
            resultjson.put("添加失败", "用户名重复");
            return ResponeResultUtil.failNotice(HWSystemCode.FAIL, resultjson);
        }
        //设置主键和密码
//		System.out.println(vo.getPassword());
        hwBaseUser.setfUserid(UUID.randomUUID().toString());

        hwBaseUser.setfPassword(loginRequestVO.getfPassword());
        //添加进入数据库
        Integer i = baseUserMapper.insert(hwBaseUser);
        System.out.println(i);
        //根据返回值决定返回信息
        if (i < 1) {
            return ResponeResultUtil.failNotice(HWSystemCode.FAIL, "添加失败");
        }

        return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS, "添加成功");
    }
*/

    /**
     *
     * @param loginRequestVO
     * @return Result
     */
    public Map<String, Object> loginByPassword(LoginRequestVO loginRequestVO) {
        //取出用户名密码
        String fAccount = loginRequestVO.getfAccount();
        String password = loginRequestVO.getfPassword();
        //获取redis
        RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);

        //根据用户名查询用户数据
        HwBaseUser hwBaseUser = new HwBaseUser();
        hwBaseUser.setfAccount(fAccount);
        HwBaseUser one = baseUserMapper.selectOne(hwBaseUser);
        // 根据用户名没查到用户或用户已逻辑删除
        if (one == null || one.getfDeletemark() == 1) {
            return ResponseResult.fail(HWSystemCode.NOTEXIST_USER);
        }

        if (one.getfEnabledmark() == 0){
            return ResponeResultUtil.failNotice(HWSystemCode.FAIL,"用户状态异常,请联系管理员");
        }

        //密码比对
        String basePass = one.getfPassword();
//		boolean validate = PassWordUtils.validatePassword(vo.getPassword(), basePass);

        if (!PassWordUtils.validatePassword(password,basePass)){
            return ResponseResult.fail(HWSystemCode.UN_MATCH);
        }
        //验证是否已登录
        String existToken = (String)redisUtil.get("loginToken" + fAccount);
        if (StringUtils.isNotBlank(existToken)) {
            redisUtil.del("loginToken" + fAccount);
            return ResponeResultUtil.fail(HWSystemCode.HASE_LOGIN);
        }
//        String token = TokenUtil.getToken(fAccount, password);
        String token =RandomNumberUtil.getNumber();
            //将token存入redis

            redisUtil.set("loginToken:"+fAccount, token,60*60);
            //将token存入cookie
//            this.saveCookie(token);

//            //将用户姓名及token存入返回对象
//            loginResponseVO.setUsername(username);

        //获取用户角色关系
        Wrapper<HwBaseUserRelation> relationEntityWrapper = new EntityWrapper<>();
        relationEntityWrapper.eq("F_UserId", one.getfUserid());
        List<HwBaseUserRelation> hwBaseUserRelations = baseUserRelationMapper.selectList(relationEntityWrapper);

        //获取用户角色的所有菜单ModuleID
        List<String> moduleIds = new ArrayList<>();
        for (HwBaseUserRelation hwBaseUserRelation : hwBaseUserRelations) {
            Wrapper<HwBaseAuthorize> authorizeWrapper = new EntityWrapper<>();
            authorizeWrapper.eq("F_RoleId", hwBaseUserRelation.getfRoleid());
            List<HwBaseAuthorize> hwBaseAuthorizes = baseAuthorizeMapper.selectList(authorizeWrapper);
            for (HwBaseAuthorize hwBaseAuthorize : hwBaseAuthorizes) {
                moduleIds.add(hwBaseAuthorize.getfObjectid());
            }
        }
        //查询单位,单位名称
        String overrunname = null;
        try {
            if (one.getfType() == 1 || one.getfType() == 2){
                Wrapper<HwBaseCountycore> countycoreWrapper = new EntityWrapper<>();
                countycoreWrapper.eq("F_CountyCoreCode",one.getfTypecode());
                HwBaseCountycore hwBaseCountycore = new HwBaseCountycore();
                hwBaseCountycore.setfCountycorecode(one.getfTypecode());
                hwBaseCountycore = countycoreMapper.selectOne(hwBaseCountycore);
                overrunname = hwBaseCountycore.getfCountycorename();
            }
            if (one.getfType() == 3){
                Wrapper<HwBaseOverrunstation> overrunstationWrapper = new EntityWrapper<>();
                overrunstationWrapper.eq("F_OverrunCode",one.getfTypecode());
                HwBaseOverrunstation hwBaseOverrunstation = new HwBaseOverrunstation();
                hwBaseOverrunstation.setfOverruncode(one.getfTypecode());
                hwBaseOverrunstation = overrunstationMapper.selectOne(hwBaseOverrunstation);
                overrunname = hwBaseOverrunstation.getfOverrunname();
            }
            if (one.getfType() == 4){
                HwBaseArea hwBaseArea = areaMapper.selectById(one.getfAreaid());
                overrunname = hwBaseArea.getfAreaname() + "交警";
                one.setfTypecode(hwBaseArea.getfAreacode());
            }
            if (one.getfType() == 5){
                HwBaseArea hwBaseArea = areaMapper.selectById(one.getfAreaid());
                overrunname = hwBaseArea.getfAreaname() + "运管";
                one.setfTypecode(hwBaseArea.getfAreacode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //redis存储工具
//        System.out.println(moduleIds);

        redisUtil.set("auth" + one.getfUserid(), moduleIds,60*60);

        Map<String,Object> responseMap = new HashMap<>();
        responseMap.put("fAccount",one.getfAccount());
        responseMap.put("token",token);
        responseMap.put("user",one);
        responseMap.put("overrunname",overrunname);
        return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS, responseMap);//登录成功
    }

    /**
     * 站点值班管理
     * @param fOverrunCode
     * @return  Station duty management
     * @date 11点53分
     */
    public Map<String, Object> StationDutyManagement(String fOverrunCode) {
        Map<String,Object> map=new HashMap<>();
        HwBaseOverrunstation hwBase = overrunstationMapper.StationDutyManagement(fOverrunCode);
        List<Map<String, Object>> list = baseUserMapper.chooseOnDuty(fOverrunCode);
        map.put("workLog",hwBase);
        map.put("option",list);
        return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS, map);
    }

    /**
     * 站点值班修改
     * @param vo
     * @return  revampManagement
     * @date 11点53分
     */
    public Map<String, Object> revampStationDutyManagement(BaseOverrunstationVO vo) {
          Wrapper<HwBaseOverrunstation> codewrapper = new EntityWrapper<HwBaseOverrunstation>();
          HwBaseOverrunstation hwBaseOverrun=new HwBaseOverrunstation();
          hwBaseOverrun.setfDbld(vo.getfDbld());
          hwBaseOverrun.setfDbldphone(vo.getfDbldphone());
          hwBaseOverrun.setfDbldZfzh(vo.getfDbldZfzh());
          hwBaseOverrun.setfDbbz(vo.getfDbbz());
          hwBaseOverrun.setfDbbzphone(vo.getfDbbzphone());
          hwBaseOverrun.setfDbldCreatetime(new Timestamp(System.currentTimeMillis()));
          codewrapper.eq("F_OverrunCode",vo.getfOverruncode());
         Integer update = overrunstationMapper.update(hwBaseOverrun, codewrapper);
            if (update==1){
                HwBaseOverrunstation hwBaseOverrunstation = overrunstationMapper.StationDutyManagement(vo.getfOverruncode());
                //hw_base_overrunStation_duty
                HwBaseOverrunstationDuty duty=new HwBaseOverrunstationDuty();
                duty.setfDutyid(RandomNumberUtil.getNumber());
                // 所属超限站编号	 F_OverrunStationID
                duty.setfOverrunstationid(hwBaseOverrunstation.getfOverruncode());
                //F_OverrunStationName	varchar	200	0	-1	0	超限站名称
                duty.setfOverrunstationname(hwBaseOverrunstation.getfOverrunname());
                //F_AreaId	varchar	50	0	-1	0	所属行政区
                duty.setfAreaid(hwBaseOverrunstation.getfAreaid());
                //F_AreaName	varchar	50	0	-1	0	所属行政区名称
                duty.setfAreaname(hwBaseOverrunstation.getfOverrunname());
                //F_Dbld	varchar	50	0	-1	0	带班领导
                duty.setfDbld(vo.getfDbld());
                //F_DbldPhone	varchar	50	0	-1	0	带班领导联系电话
                duty.setfDbldphone(vo.getfDbldphone());
                //F_dbld_Zfzh	varchar	50	0	-1	0	带班领导执法证号
                duty.setfDbldZfzh(vo.getfDbldZfzh());
                // F_Dbbz	varchar	50	0	-1	0	当班班长
                duty.setfDbbz(vo.getfDbbz());
                //F_DbbzPhone	varchar	50	0	-1	0	当班班长联系电话
                duty.setfDbbzphone(vo.getfDbbzphone());
                //F_CreateAccount	varchar	50	0	-1	0	添加人accountID
                duty.setfCreateaccount(vo.getfCreateuserid());
                //F_CreateUserName	varchar	50	0	-1	0	添加人姓名
                duty.setfCreateusername(vo.getfCreateusername());
                //F_CreateTime	datetime	0	0	-1	0	添加时间
                duty.setfCreatetime(new Timestamp(System.currentTimeMillis()));
                Integer insert = hwBaseOverrunstationDutyMapper.insert(duty);
                if (insert!=1){
                    return ResponeResultUtil.failNotice(HWSystemCode.FAIL,"修改失败");
                }
            }else {
                return ResponeResultUtil.failNotice(HWSystemCode.FAIL,"修改失败");
            }
         return ResponeResultUtil.success(HWSystemCode.SUCCESS);
    }


    //将令牌存储到cookie
//    private void saveCookie(String token) {
//        cookieMaxAge = 3600;
//        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//        //HttpServletResponse response,String domain,String path, String name, String value, int maxAge,boolean httpOnly
//
//        CookieUtil.addCookie(response, "192.168.0.168", "/", "uid", token, cookieMaxAge, false);
//
//    }

}
